<template>
    <div class="" v-if="state !== 'hidden'">

        <el-form ref="form" :model="form" :label-width="canWrite ? '115px':'auto'"
                 :class="canWrite ? 'write-form':'read-form'"
                 :label-position="'left'">

            <div class="card-wrap flex-column justify-end card-padding" >
                <el-descriptions :column="2">
                    <el-descriptions-item label="信审编号">
                        <span class="table-blue-text"
                              @click="_toPage({
                                name: 'LetterReviewDetail',
                                query: {
                                  applicationNo: form.applicationNo
                                }
                              })">{{form.applicationNo|filterNull}}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="额度申请编号">
                        <span class="table-blue-text"
                              @click="
                                    _toPage({
                                        path: '/quota/ApplyDetails',
                                        name: 'ApplyDetails',
                                        query: {
                                            calcSchemeId: form.calcSchemeId,
                                            // processId: form.processId,
                                        },
                                    })
                                ">{{form.calcSchemeCode|filterNull}}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="订单编号">
                        <span class="table-blue-text"
                              @click="
                                    _toPage({
                                        name: 'OrderDetails',
                                        query: {
                                                type: form.carType,
                                                orderId: form.orderId,
                                                calcSchemeId: form.calcSchemeId,
                                            },
                                        })
                                ">{{form.orderCode|filterNull}}</span>
                    </el-descriptions-item>
                </el-descriptions>
            </div>
            <div class="card-wrap flex-column justify-end card-padding"
                 v-for="(fitem, findex) in form.contractList" :key="findex">

                <div class="card-title-wrap">
                    <span>{{ fitem.contractTemplateTypeStr|filterNull }}</span>
                    <span></span>
                </div>

                <el-row :gutter="10">
                    <el-col :span="24">
                        <el-form-item label="是否电子签:" prop="electronicSignType"
                                      :rules="canWrite ? {
                                         required: true,
                                         message: '请选择是否电子签',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, fitem.electronicSignType, callback)
                                       }:{}">
                            <el-radio-group @change="$forceUpdate()" v-if="canWrite" v-model="fitem.electronicSignType">
                                <template v-for="dict in dict.type.order_electronic_sign_type">
                                    <el-radio :label="dict.value">{{ dict.label }}</el-radio>
                                </template>
                            </el-radio-group>
                            <span v-else><dict-tag
                                :options="dict.type.order_electronic_sign_type"
                                :value="fitem.electronicSignType"/></span>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="10" v-if="1==fitem.electronicSignType">

                    <el-col :span="24">
                        <span class="mini-title">发起方</span>
                    </el-col>

                    <el-col :span="24" v-if="fitem.uniData && fitem.uniData.configList">

                        <div v-for="(titem, tindex) in fitem.uniData.configList" :key="tindex">

                            <!--                            节点类型：(1经办人签字，2法定代表人签字，3个人审批，4企业签章)-->
                            <div class="task-wrap" v-if="1==titem.taskType">

                                <el-row :gutter="10" style="display: flex;align-items: center">
                                    <el-col :span="4">
                                        <span class="task-title">经办人签字</span>
                                    </el-col>
                                    <el-col :span="10">
                                        <el-form-item label="经办人姓名:" prop="operatorName"
                                                      :rules="canWrite ? {
                                                         required: true,
                                                         message: '请选择经办人姓名',
                                                         trigger: 'change',
                                                         validator: (rule, value, callback) => validData(rule, fitem.uniData.operatorName, callback)
                                                       }:{}">

                                            <el-select filterable clearable
                                                @change="operatorChange($event, fitem)"
                                                v-if="canWrite" style="width: 100%" v-model="fitem.uniData.operatorId" placeholder="请选择">
                                                <el-option
                                                    v-for="item in memberList"
                                                    :key="item.userId"
                                                    :label="item.nickName"
                                                    :value="item.userId">
                                                </el-option>
                                            </el-select>

                                            <span v-else>{{ fitem.uniData.operatorName|filterNull }}</span>
                                        </el-form-item>
                                    </el-col>

                                    <el-col :span="10">
                                        <el-form-item label="经办人手机号:" prop="operatorPhone"
                                                      :rules="canWrite ? {
                                                         required: true,
                                                         message: '请输入经办人手机号',
                                                         trigger: 'blur',
                                                         validator: (rule, value, callback) => validData(rule, fitem.uniData.operatorPhone, callback)
                                                       }:{}">
                                            <el-input v-if="canWrite" maxlength="11"
                                                      @input="value=>{fitem.uniData.operatorPhone=value.replace(/[^\d]/g,'');$forceUpdate()}"
                                                      v-model.trim="fitem.uniData.operatorPhone"
                                                      placeholder="请输入经办人手机号"></el-input>
                                            <span v-else>{{ fitem.uniData.operatorPhone|filterNull }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </div>
                            <div class="task-wrap" v-else-if="2==titem.taskType">
                                <el-row :gutter="10" style="display: flex;align-items: center">
                                    <el-col :span="5">
                                        <span class="task-title">法定代表人签字</span>
                                    </el-col>
                                    <el-col :span="9">
                                        <el-form-item label="法人姓名:" prop="lpName"
                                                      :rules="canWrite ? {
                                                         required: true,
                                                         message: '请选择法人姓名',
                                                         trigger: 'change',
                                                         validator: (rule, value, callback) => validData(rule, fitem.uniData.lpName, callback)
                                                       }:{}">

                                            <el-select filterable clearable
                                                @change="lpChange($event, fitem)"
                                                v-if="canWrite" style="width: 100%" v-model="fitem.uniData.lp" placeholder="请选择">
                                                <el-option
                                                    v-for="item in memberList"
                                                    :key="item.userId"
                                                    :label="item.nickName"
                                                    :value="item.userId">
                                                </el-option>
                                            </el-select>
                                            <span v-else>{{ fitem.uniData.lpName|filterNull }}</span>
                                        </el-form-item>
                                    </el-col>

                                    <el-col :span="10">
                                        <el-form-item label="法人手机号:" prop="lpPhone"
                                                      :rules="canWrite ? {
                                                         required: true,
                                                         message: '请输入法人手机号',
                                                         trigger: 'blur',
                                                         validator: (rule, value, callback) => validData(rule, fitem.uniData.lpPhone, callback)
                                                       }:{}">
                                            <el-input v-if="canWrite" maxlength="11"
                                                      @input="value=>{fitem.uniData.lpPhone=value.replace(/[^\d]/g,'');$forceUpdate()}"
                                                      v-model.trim="fitem.uniData.lpPhone"
                                                      placeholder="请输入法人手机号"></el-input>
                                            <span v-else>{{ fitem.uniData.lpPhone|filterNull }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </div>

                            <div class="task-wrap" v-else-if="3==titem.taskType">
                                <span class="task-title">个人审批</span>
                                <el-table style="margin-top: 10px" :data="titem.saveList" border size='mini'>
<!--                                    <el-table-column align="center" type="index" width="38"/>-->
                                    <el-table-column align="center" label="审批人"
                                                     prop="approvalName"/>
                                    <el-table-column align="center" label="联系方式" prop="approvalPhone"/>
                                </el-table>
                            </div>

                            <div class="task-wrap" v-else-if="4==titem.taskType">
                                <span class="task-title">企业签章</span>
                                <el-table style="margin-top: 10px" :data="titem.saveList" border size='mini'>
<!--                                    <el-table-column align="center" type="index" width="38"/>-->
                                    <el-table-column align="center" label="签章人"
                                                     prop="approvalName"/>
                                    <el-table-column align="center" label="联系方式" prop="approvalPhone"/>
                                </el-table>
                            </div>

                        </div>

                    </el-col>

                    <el-col :span="24">
                        <span class="mini-title">个人接收方</span>
                    </el-col>

                    <el-col :span="8" v-if="fitem.recipientList">
                        <el-form-item label="接收人名称:" prop="recipientName">
                            <el-input v-if="canWrite"
                                      v-model.trim="fitem.recipientList[0].recipientName" placeholder="请输入接收人名称"></el-input>
                            <span v-else>{{ fitem.recipientList[0].recipientName|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8" v-if="fitem.recipientList">
                        <el-form-item label="接收人手机号:" prop="recipientMobile">
                            <el-input v-if="canWrite" maxlength="11"
                                      @input="value=>fitem.recipientList[0].recipientMobile=value.replace(/[^\d]/g,'')"
                                      v-model.trim="fitem.recipientList[0].recipientMobile"
                                      placeholder="请输入接收人手机号"></el-input>
                            <span v-else>{{ fitem.recipientList[0].recipientMobile|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="24">
                        <span class="mini-title">接收方</span>
                    </el-col>

                    <el-col :span="24">
                        <el-form-item label="类型:" prop="partyType"
                                      :rules="canWrite ? {
                                         required: true,
                                         message: '请选择类型',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, fitem.partB.partyType, callback)
                                       }:{}">
                            <el-radio-group @change="partyChange($event, fitem)" v-if="canWrite" v-model="fitem.partB.partyType">
                                <template v-for="dict in dict.type.order_contract_party_type">
                                    <el-radio :label="dict.value">{{ dict.label }}</el-radio>
                                </template>
                            </el-radio-group>
                            <span v-else><dict-tag
                                :options="dict.type.order_contract_party_type"
                                :value="fitem.partB.partyType"/></span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8" v-if="2==fitem.partB.partyType">
                        <el-form-item label="企业名称:" prop="companyName"
                                      :rules="canWrite ? {
                                         required: true,
                                         message: '请输入企业名称',
                                         trigger: 'blur',
                                         validator: (rule, value, callback) => validData(rule, fitem.partB.companyName, callback)
                                       }:{}">
                            <el-input v-if="canWrite"
                                      v-model.trim="fitem.partB.companyName"
                                      placeholder="请输入企业名称"></el-input>
                            <span v-else>{{ fitem.partB.companyName|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8" v-if="2==fitem.partB.partyType">
                        <el-form-item label="经办人名称:" prop="agentName"
                                      :rules="canWrite ? {
                                         required: true,
                                         message: '请输入经办人名称',
                                         trigger: 'blur',
                                         validator: (rule, value, callback) => validData(rule, fitem.partB.agentName, callback)
                                       }:{}">
                            <el-input v-if="canWrite"
                                      v-model.trim="fitem.partB.agentName"
                                      placeholder="请输入经办人名称"></el-input>
                            <span v-else>{{ fitem.partB.agentName|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8" v-if="1==fitem.partB.partyType">
                        <el-form-item label="接收人名称:" prop="recipientName"
                                      :rules="canWrite ? {
                                         required: true,
                                         message: '请输入接收人名称',
                                         trigger: 'blur',
                                         validator: (rule, value, callback) => validData(rule, fitem.partB.recipientName, callback)
                                       }:{}">
                            <el-input v-if="canWrite"
                                      v-model.trim="fitem.partB.recipientName"
                                      placeholder="请输入接收人名称"></el-input>
                            <span v-else>{{ fitem.partB.recipientName|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8" v-if="2==fitem.partB.partyType">
                        <el-form-item label="经办人手机号:" prop="agentMobile"
                                      :rules="canWrite ? {
                                         required: true,
                                         message: '请输入经办人手机号',
                                         trigger: 'blur',
                                         validator: (rule, value, callback) => validData(rule, fitem.partB.agentMobile, callback)
                                       }:{}">
                            <el-input v-if="canWrite" maxlength="11"
                                      @input="value=>fitem.partB.agentMobile=value.replace(/[^\d]/g,'')"
                                      v-model.trim="fitem.partB.agentMobile"
                                      placeholder="请输入经办人手机号"></el-input>
                            <span v-else>{{ fitem.partB.agentMobile|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8" v-if="1==fitem.partB.partyType">
                        <el-form-item label="接收人手机号:" prop="recipientMobile"
                                      :rules="canWrite ? {
                                         required: true,
                                         message: '请输入接收人手机号',
                                         trigger: 'blur',
                                         validator: (rule, value, callback) => validData(rule, fitem.partB.recipientMobile, callback)
                                       }:{}">
                            <el-input v-if="canWrite" maxlength="11"
                                      @input="value=>fitem.partB.recipientMobile=value.replace(/[^\d]/g,'')"
                                      v-model.trim="fitem.partB.recipientMobile"
                                      placeholder="请输入接收人手机号"></el-input>
                            <span v-else>{{ fitem.partB.recipientMobile|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="24" v-if="2==fitem.partB.partyType">
                        <el-form-item label="签署动作:" prop="checkedList"
                                      :rules="canWrite ? {
                                         type: 'array',
                                         required: true,
                                         message: '请选择签署动作',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, fitem.checkedList, callback)
                                       }:{}">

                            <el-checkbox-group v-if="canWrite"
                                v-model="fitem.checkedList">
                                <el-checkbox @change="operCheck($event, fitem)" :label="1" :key="1">经办人签字</el-checkbox>
                                <el-checkbox @change="comCheck($event, fitem)" :label="4" :key="4">企业签章</el-checkbox>
                            </el-checkbox-group>

                            <span v-else>{{1==fitem.agentChbType?'经办人签字':''}}{{1==fitem.signatureChbType?'  企业签章':''}}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="24">
                        <el-form-item label="合同状态:" prop="contractStatusStr">
                            <span>{{ fitem.contractStatusStr|filterNull }}</span>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="10">
                    <el-col :span="24" v-if="1==fitem.electronicSignType || 2==fitem.electronicSignType">
                        <el-form-item label="查看合同:" style="width: 100%">
                            <ImageCommon :limit="1" disabled v-model="fitem.contractFilePrimal"></ImageCommon>
                        </el-form-item>
                    </el-col>
                </el-row>

            </div>

        </el-form>

    </div>
</template>

<script>
import {
    contractLockSignConfig,
    getInfoByDeptId,
    getUserList,
    getUserListNoEncrypt
} from "@/api/contractTemplate/electronicContract";

export default {
    dicts: ['order_contract_type', 'order_electronic_sign_type', 'order_contract_party_type', 'quota_source_business'],
    props: {
        value: {
            type: Object,
            default: () => ({}),
        },
        state: {
            default: "write",
        },
    },
    computed: {
        form: {
            get() {
                return this.value;
            },
            set(value) {
                this.$emit("input", value);
            },
        },
        canWrite() {
            return 'write' == this.state
        }
    },
    watch:{
        form:{
            deep:true,
            immediate:true,
            handler(val){
                if(this.firstEnter && val && val.orderId){
                    val.contractList = val.contractList.map(item=>{
                        if(item.recipientList==undefined||item.recipientList==null){
                            item.recipientList = [{}]
                        }
                        return item
                    })

                    this.firstEnter = false
                    this.getCompanyName()
                    this.getSignData()
                    this.getMemberList()
                }
            }
        }
    },
    data() {
        return {
            firstEnter:true,
            memberList:[],
            companyName:null
        };
    },
    methods: {
        //1个人  2企业
        partyChange(val, fitem){
            if(1==val){
                // fitem.partB.companyName=null;
                // fitem.partB.agentName=null;
                // fitem.partB.agentMobile=null;
                fitem.checkedList = [];
                fitem.agentChbType = 2
                fitem.signatureChbType = 2

            }else if(2==val){
                // fitem.partB.recipientName=null;
                // fitem.partB.recipientMobile=null;
            }

            this.$forceUpdate();
        },
        operCheck(val, fitem){
            fitem.agentChbType = val?1:2
            // fitem.configList = fitem.checkedList.map(item=>{
            //     return {
            //         taskType:item
            //     }
            // })
            console.log('operCheck', val, fitem.checkedList)

            this.$forceUpdate()
        },
        comCheck(val, fitem){
            fitem.signatureChbType = val?1:2
            // fitem.configList = fitem.checkedList.map(item=>{
            //     return {
            //         taskType:item
            //     }
            // })
            console.log('comCheck', val, fitem.checkedList)

            this.$forceUpdate()
        },

        operatorChange(val, fitem){
            let find = this.memberList.find(item=>val==item.userId);
            if(find){
                fitem.uniData.operatorName = find.nickName
                fitem.uniData.operatorPhone = find.phonenumber
            }else{
                fitem.uniData.operatorName = null
                fitem.uniData.operatorPhone = null
            }
            this.$forceUpdate()
        },
        lpChange(val, fitem){
            let find = this.memberList.find(item=>val==item.userId);
            if(find){
                fitem.uniData.lpName = find.nickName
                fitem.uniData.lpPhone = find.phonenumber
            }else{
                fitem.uniData.lpName = null
                fitem.uniData.lpPhone = null
            }
            this.$forceUpdate()
        },
        getCompanyName(){
            getInfoByDeptId(this.form.lessorId).then(res=>{
                this.companyName = res.data?.name??null
            })
        },
        getSignData() {
            contractLockSignConfig({
                configStatus: 1,
                lessorId: this.form.lessorId,
                businessConfigType: this.form.sourceBusinessType == 1 ? 2 : this.form.sourceBusinessType == 2 ? 1 : null,//1渠道业务,2自营业务
            }).then(res => {
                // this.uniData = res.data

                this.form.contractList = this.form.contractList.map(item=>{
                    item.uniData = _.cloneDeep(res.data)
                    item.checkedList = []
                    return item
                })

                if(res.data.configList == undefined || res.data.configList == null || res.data.configList.length<=0){
                    this.$modal.msgError("暂未配置签署流程，无法进行电子合同签署。请联系管理员，完成签署流程配置。")
                }
                this.$forceUpdate()
            }).catch(e=>{
                this.$modal.msgError("暂未配置签署流程，无法进行电子合同签署。请联系管理员，完成签署流程配置。")
            })
        },
        getMemberList() {
            getUserListNoEncrypt({deptId: this.form.lessorId}).then(res=>{
                this.memberList = res.data
            })
        },
        validData(rule, value, callback) {
            if(value instanceof Array && value.length<=0){
                callback(new Error(rule.message));
            }else if (rule.required && !value) {
                callback(new Error(rule.message));
            } else {
                callback();
            }
        },
        async valid() {
            // console.log('this.value', this.value)

            return new Promise((resolve) => {
                if ('write' == this.state) {
                    this.$refs["form"].validate(valid => {
                        this.form.contractList = this.form.contractList.map(item=>{
                            let obj = {}

                            obj.subject = item.contractTemplateTypeStr
                            obj.lessorVo = {
                              // companyId:this.form.lessorId,
                              // companyName:this.form.lessorName,
                              companyName:this.companyName,
                              lpName:item.uniData.lpName,
                              lpPhone:item.uniData.lpPhone,
                              operatorName:item.uniData.operatorName,
                              operatorPhone:item.uniData.operatorPhone,
                              configList:item.uniData.configList.map((litem,lindex)=>{
                                litem.configSort = lindex
                                return litem
                              })
                            }
                            //partyType  1个人  2企业
                            let flag = item.partB.partyType
                            obj.lesseeVo = {
                              // companyId:2==flag?'':null,
                              companyName:2==flag?item.partB.companyName:null,
                              operatorName:2==flag?item.partB.agentName:null,
                              operatorPhone:2==flag?item.partB.agentMobile:null,
                              receiveUserName:1==flag?item.partB.recipientName:null,
                              receivePhone:1==flag?item.partB.recipientMobile:null,
                              configList:item.checkedList.map(citem=>{
                                return {
                                  taskType:citem
                                }
                              }),
                            }
                            obj.receiveVo = {
                              receiveUserName:item.recipientList[0].recipientName,
                              receivePhone:item.recipientList[0].recipientMobile,
                            }

                            console.log('处理玩的obj', obj)

                            item.partA.confSnapshoot = JSON.stringify(obj)

                            //否电子签时，把contractFile置为null
                            if(2==item.electronicSignType){
                              item.contractFile = null
                            }else {
                              item.contractFile = item.contractFilePrimal
                            }

                            return item
                        })


                        let personRepeat = this.form.contractList.find(item =>
                            1==item.electronicSignType && 1 == item.partB.partyType
                            && (item.recipientList[0].recipientName == item.partB.recipientName
                            || item.recipientList[0].recipientMobile == item.partB.recipientMobile
                            ));
                        if(personRepeat){
                            this.$modal.msgError("个人接收方和接收方信息不得相同！")
                            resolve(false)
                            return;
                        }

                        let companyRepeat = this.form.contractList.find(item =>
                            1==item.electronicSignType && 2 == item.partB.partyType
                            && this.companyName == item.partB.companyName);
                        if(companyRepeat){
                            this.$modal.msgError("企业名称不得相同！")
                            resolve(false)
                            return;
                        }

                        // console.log('通过了执行提交', valid)
                        resolve(valid);
                    });
                } else {
                    resolve(true)
                }
            })
        },
    }
};
</script>


<style lang="scss" scoped>
::v-deep .el-form--label-top .el-form-item__label {
    padding: 0;
}


.icon_add {
    margin-left: 10px;
    cursor: pointer;
}

::v-deep .read-form .el-form-item__label-wrap,
::v-deep .read-form .el-form-item__content {
    margin-left: 0 !important;
}

.task-wrap{
    margin: 15px 10px;
    padding: 20px 20px;
    box-sizing: border-box;
    border: 1px solid rgba(215, 215, 215, 1);
    background-color: rgba(255, 255, 255, 1);
    border-radius: 4px;

    .task-title{
        font-size: 14px;
    }

    .el-form-item {
        margin-bottom: 0px !important;
        width: 100%;
    }
}
.write-form .el-form-item {
    //margin-bottom: 13px !important;
    width: 100%;
}
</style>
